package common

import (
	"config-client-v1/init/global"
	"config-client-v1/utils/tools"
	"github.com/gin-gonic/gin"
	"path"
	"path/filepath"
)

type Common struct {
}

func (con Common) UploadFile(ctx *gin.Context) {
	uploadType := ctx.PostForm("editor")
	file, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    1,
			"message": err.Error(),
		})
		return
	}
	// 上传文件到指定的目录，在项目根路径下创建/media/upload文件夹
	filename := file.Filename
	extension := filepath.Ext(filename)
	randomName := tools.GetNano() + tools.GetRandomString(10)
	keyPath := "tmp/" + randomName + extension
	if uploadType == "editor" {
		keyPath = "upload/editor/" + randomName + extension
	}
	absPath := path.Join(global.StaticPath, keyPath)
	tools.CreateDir(filepath.Dir(absPath))
	err = ctx.SaveUploadedFile(file, absPath)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    1,
			"message": "SaveUploadedFile error",
			"data":    err.Error(),
		})
		return
	}
	//ctx.String(200, "upload success! "+filename)
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"name": filename,
			"url":  keyPath,
		},
	})
}
